import { _decorator, Component, Sprite, UITransform } from 'cc'
import { DIRECTION_ENUM, DIRECTION_ORDER_ENUM, ENTITY_STATE_ENUM, ENTITY_TYPE_ENUM, PARAMS_NAME_ENUM } from '../Enum'
import { IEntity } from '../Levels'
import { PlayerStateMachine } from '../Scripts/Player/PlayerStateMachine'
import { TILE_HEIGHT, TILE_WIDTH } from '../Scripts/Tile/TileManager'
import { StateMachine } from './StateMachine'
import { randomString } from '../Utils'
import DataManager from '../Runtime/DataManager'

const { ccclass, property } = _decorator

/**
 * Predefined variables
 * Name = EntityManager
 * DateTime = Thu Jul 07 2022 17:30:34 GMT+0800 (中国标准时间)
 * Author = Zero_Y
 * FileBasename = EntityManager.ts
 * FileBasenameNoExtension = EntityManager
 * URL = db://assets/Scripts/Player/EntityManager.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */

@ccclass('EntityManager')
export class EntityManager extends Component {
  id: string = randomString(12)
  // 坐标
  x: number = 0
  y: number = 0
  // 状态机
  fsm: StateMachine
  // 人物当前方向
  private _direction: DIRECTION_ENUM
  // 人物当前状态
  private _state: ENTITY_STATE_ENUM

  type: ENTITY_TYPE_ENUM

  get direction() {
    return this._direction
  }

  set direction(newDirection) {
    this._direction = newDirection
    // 设置fsm化动画
    this.fsm.setParams(PARAMS_NAME_ENUM.DIRECTION, DIRECTION_ORDER_ENUM[newDirection])
  }
  get state() {
    return this._state
  }
  set state(newState) {
    this._state = newState
    this.fsm.setParams(newState, true)
  }

  async init(params: IEntity) {
    // 渲染人物
    const sprite = this.node.addComponent(Sprite)
    sprite.sizeMode = Sprite.SizeMode.CUSTOM
    const transform = this.getComponent(UITransform)
    transform.setContentSize(TILE_WIDTH * 4, TILE_HEIGHT * 4)

    // this.fsm = this.addComponent(PlayerStateMachine)
    // await this.fsm.init()
    this.x = params.x
    this.y = params.y
    this.type = params.type
    // 设置初始方向
    this.direction = params.direction
    // 设置fsm化动画
    this.state = params.state
  }
  update() {
    // 更新移动位置，由于人物占4个格子居中需要偏移
    this.node.setPosition(this.x * TILE_WIDTH - TILE_WIDTH * 1.5, -this.y * TILE_HEIGHT + TILE_HEIGHT * 1.5)
  }
  onDestroy() {}
}
